%% fig 6b example place cell sequence
rat={'jsrat1','jsrat2','jsrat3','jsrat4','jsrat5'};
figure('position',[  379   121   269   449],'color','w')
for irat=3%1:length(rat)
    cd (['/media/Big2/processedData/newtemplate/',rat{irat}])
    
    load PlFields.mat
    load RUNTemplate2Reverse1pk20_reorder2hzcb10cm.mat
    
    %%F
    for irun=1%:2
        binsize=2; % cm
        
        seq=templt_seq{irun};
        plf=squeeze(PlFields(seq,1,irun,:));
        binedge=[find(sum(plf)>0,1,'first'),find(sum(plf)>0,1,'last')];
        plf=plf(:,binedge(1):binedge(2));
        
        %         subplot(2,length(rat),irat+(length(rat))*(irun-1))
        for i=1:length(seq)
            x=[1:size(plf,2),1]*binsize;
            y=plf(i,:);
            y=[y(:)',y(1)];
            y=y/max(y);
            patch( x,y+i,'r');hold on
        end
        set(gca,'xtick',0:50:200)
        title([rat{irat},'run',num2str(irun)])
    end
end
setaxisformal(gca,12,0)
% savepdf(gcf,'/media/Big1/15tracks/figures/example_run_sequence.fig')
% savepdf(gcf,'/media/Big1/15tracks/figures/example_run_sequence.pdf')

%% fig 6e 6f s6a s6b;  markov prediction of 15 track
clear
pop_tag='diff'; % fig 6e 6f 
% pop_tag='same'; % fig s6a s6b
load(['/media/Big1/15tracks/MarkovPrediction/NoRunPercentile',pop_tag,'.mat']);

%each sleep

f1=figure('position',[ 125   272   511   668]);
for isleep=1:size(per1,2)
    p1=squeeze(per1(:,isleep,:));
    p1=p1(:);
    subplot(3,2,isleep)
    edge=0:5:100;
    histogram(p1*100,edge);hold on;
    plot([0,100],[1,1]*length(p1)/length(edge),'k:');
    xlabel('percentile');ylabel('# seq');
    title(['sleep',num2str(isleep)])
end
subplot(313)
shadedErrorBar(1:length(per1sleep_mean),per1sleep_mean*100,per1sleep_se*100,{'b'});hold on;
sigstar(groupPair,pval);xlabel('Sleep');ylabel('percentile'); box off;
set(gca,'xlim',[0,length(per1sleep_mean)+1],'xtick',1:4);
suptitle(nameTag);
setaxisformalAll(12);
% savepdf(f1,['/media/Big1/15tracks/figures/markovprediction',pop_tag,'_per_norun_area.pdf'])

tmp=per1(:,1,:);markovResultsTest(per1(:))
[testout,testgroupPair,testpval,testp1]=test_multigroup_rank(reshape(permute(per1,[1,3,2]),size(per1,1)*size(per1,3),size(per1,2)))
%% fig 6c 6d. example long seq prob.
clear
savepath='/media/Big1/15tracks/figures/';

% load('/media/Big1/processedData/figures/matfile/gdrat1_ForKefei_Pre3ArmSleep1_DurLim_centerofmassSpk2cell_diffpop_alongmultipeakmax31by1_conditional_prob_percent.mat')
% load('/media/Big1/processedData/figures/exampleConditionalProbmatrix/ForKefei_Pre3ArmSleep1_DurLim_centerofmassSpkcb2hz10cm_2cell_diffpop_alongtimemax31by1_conditional_prob_percent.mat')
% load('/media/Big1/processedData/figures/exampleConditionalProbmatrix/Pre3ArmsSleep2_DurLim_centerofmassSpkfrctrl2hz10cm_2cell_diffpop_alongtimemax31by1_conditional_prob_percent.mat',...
%     'letna');
load('/media/Big2/processedData/figures/exampleConditionalProbmatrix/Pre3ArmsSleep1_DurLim_centerofmassSpkp1norm2hz10cm_2cell_diffpop_alongtimemax31by1_conditional_prob_percent.mat',...
    'letna');
% load('/media/Big1/processedData/figures/exampleConditionalProbmatrix/Pre3ArmsSleep1_DurLim_centerofmassSpkp1norm2hz10cm_2cell_diffpop_alongtimemax31by1_conditional_prob_percent.mat',...
%     'letna');
fontsize=12;

letn=letna{2};
% m=median(letn);

letn=letn/sum(letn);
logletn=log10(letn);

letns=sort(letn);
logletns=sort(logletn);

edge1=[linspace((min(letn)),(max(letn)),500)];
[ndis1]=histcounts(letn,edge1);
limi1=[0,max(ndis1)*1.2];

edge=[linspace((min(logletn)),(max(logletn)),200)];
[ndis]=histcounts(logletn,edge);
limi=[0,max(ndis)*1.2];

plim1=[edge1(1),edge1(end)];
plim=[edge(1),edge(end)];

f2=figure('color','w','position',[115   373   842   431]);
subplot(122)
h0= plot(edge(2:end),ndis,'linewidth',2);
hold on;
% h2=plot([1,1]*logletn(end),limi,'g','linewidth',2); % GREEN: template position
h2=plot([1,1]*logletn(end),limi,'g','linewidth',2); % GREEN: template position
legend([h0;h2],{'Random';'Real'});legend('boxoff','location','best')
set(gca,'xlim',plim,'ylim',limi,'box','off','tickdir','out'...
    ,'linewidth',1.5,'fontsize',fontsize);   axis square
xlabel('log probability');ylabel('# of seq');
subplot(121)
h0=plot(logletns,'.','linewidth',2);
hold on
h2=plot([1]*find(logletns==logletn(end)),logletn(end),'go','linewidth',2);
h3=plot([1,1]*find(logletns==logletn(end)),[plim(1),logletn(end)],'g','linewidth',1);
set(gca,'box','off','ylim',plim,'xlim',[0,length(logletns)],'tickdir','out',...
    'linewidth',1.5,'fontsize',fontsize);   axis square;
ylabel('log probability');xlabel('Sequences');
prc=calc_prctile(letn(1:end-1),letn(end));
title(sprintf('percentile=%.4g',prc*100));

% saveas(f1,fullfile(savepath,'exampleLongRandSeqProb.fig'))
% saveas(f1,fullfile(savepath,'exampleLongRandSeqProb.png'))
% saveas(f2,fullfile(savepath,'exampleLongSeqProb.fig'))
% saveas(f2,fullfile(savepath,'exampleLongSeqProb.png'))
% savepdf(f2,fullfile(savepath,'exampleLongSeqProb.pdf'));

%% fig s6c s6d; markov prediction of 15 track  === add run
clear
pop_tag1='diff'; % fig s6c 
% pop_tag1='same'; % fig s6d
% edit SCRIPT_markov_cm_and_1stspk3normp1_15track.m  %%@ summary types
load(['/media/Big1/15tracks/MarkovPrediction/AddRunPercentileAll',pop_tag1,'.mat']);

nameTagAll=nameTags;

%  nameTags={'AddRun','RunOnly','NoRun','AddRunSameOri','AddRun90deg','RunOnlySameOri','RunOnly90deg'};
% nameTags={'NoRun','AddRun','AddRunSameOri'};
nameTags={'NoRun','AddRun90deg','AddRunSameOri'};
% nameTags={'NoRun'};
% nameTags={'AddRunPreTrack','AddRunFutureTrack'};

[~,nameInd]=ismember(nameTags,nameTagAll);

per1sleep_all=per1sleep_all(nameInd,:);

f1=figure;
for imode=1:length(nameTags)
    errorbar(per1sleep_all{imode,2}*100,per1sleep_all{imode,3}*100);hold on;
end
%    errorbar(per1sleep_all{2,2},per1sleep_all{2,3});
ptmp=nan(size(per1sleep_all{1,1},1),1);
for i=1:length(ptmp)
    ptmp(i)=signrank(per1sleep_all{1,1}(i,:), per1sleep_all{2,1}(i,:));
    %       signrank(per1sleep_all{3,1}(i,:), per1sleep_all{2,1}(i,:))
end
sigstar1(1:4,ptmp,max([per1sleep_all{1,2};per1sleep_all{2,2}]));
legend(nameTags);
xlabel('sleep');ylabel('percentile');
set(gca,'ylim',[min([per1sleep_all{1,2},per1sleep_all{2,2}])*0.5, ...
    max([per1sleep_all{1,2},per1sleep_all{2,2}])*1.5]*100,'xlim',[0,5]);
setaxisformalAll

% f2=figure('color','w','position',[553    71   757   808]);
% for isleep=1:4
%     subplot(2,2,isleep)
%     tmpm=cell2mat(per1sleep_all(:,2));
%     tmpse=cell2mat(per1sleep_all(:,3));
%     errorbarformal(1:size(tmpm,1),tmpm(:,isleep)*100,tmpse(:,isleep)*100);
%     tmp=cat(3,per1sleep_all{:,1});
%     [out,groupPair,pval]=test_multigroup_pairwise(squeeze(tmp(isleep,:,:)));
%     sigstar(groupPair,pval);
%     set(gca,'xlim',[0,4],'xtick',1:3,'xticklabel',nameTags,'XTickLabelRotation',30);
%     title(['sleep',num2str(isleep)]);
%     
%     ylabel('percentile');
%     ylimdata=get(gca,'YLim');ylimdata(1)=[min(tmpm(:))-max(tmpse(:))]*100;
%     set(gca,'xticklabelrotation',30,'ylim',ylimdata,'box','off');
%     
% end
% setaxisformalAll



f2=figure('color','w','position',[ 109   361   544   440]);
fcolor=jet(3);
grouppairAll=[];pvalAll=[];ylimdata1=100;
for isleep=1:4
%     subplot(2,2,isleep)
    tmpm=cell2mat(per1sleep_all(:,2));
    tmpse=cell2mat(per1sleep_all(:,3));
    h=[];
    for j=1:3
    h1=errorbarformal(j+(isleep-1)*5,tmpm(j,isleep)*100,tmpse(j,isleep)*100,[],fcolor(j,:),0.8); hold on;
    h=[h;h1(1)];
    end
    tmp=cat(3,per1sleep_all{:,1});
    [out,groupPair,pval]=test_multigroup_pairwise(squeeze(tmp(isleep,:,:)));
    for j=1:length(groupPair);groupPair{j}=groupPair{j}+(isleep-1)*5;end
   grouppairAll=[grouppairAll;groupPair]; pvalAll=[pvalAll;pval];
   ylimdata1=min([ylimdata1,  [min(tmpm(:))-max(tmpse(:))]*100]);
end
 sigstar(grouppairAll,pvalAll); hold on;
 ylimdata=get(gca,'YLim');ylimdata=[ylimdata1-2,ylimdata(2)];
% axis(gca,'tight')
disp(pvalAll([2,5,8,11]));
 ylabel('percentile');
set(gca,'xticklabelrotation',0,'box','off','xtick',2:5:20,...
        'xticklabel',{'Sleep1','Sleep2','Sleep3','Sleep4'},'ylim',ylimdata,'ytick',0:10:100);
    legend(h,nameTags,'location','best')
setaxisformalAll(12,0);


f3=figure('color','w','position',[ 109   361   544   440]);
ydatac=per1sleep_all(:,1);
ydatac=cat(3,ydatac{:});
ydatac=permute(ydatac,[3,1,2]);
ydata=cellfun(@(x) squeeze(x),mat2cell(ydatac,ones(size(ydatac,1),1),ones(size(ydatac,2),1),size(ydatac,3)),'uniformoutput',false);
[ydata,gr]=cell2group(ydata(:));
% [m,se]=splitapply(@mean_se,ydata,gr);
xdata=[1,2,3,6,7,8,11,12,13,16,17,18];
% for ir=1:length(xdata);gr(gr==ir)=xdata(ir);end
[hdot,hbar]=plot_errorbar_with_data(ydata*100,gr,[],xdata); hold on;
% h=boxplot(ydata,gr,'symbol','.');
% distributionPlot(ydata,'groups',gr,'histOpt',1,'divFactor',15);
fcolor=jet(3);
set(hbar(1),'CData',repmat(fcolor,4,1),'EdgeColor','flat');
hbar(2)
grouppairAll=[];pvalAll=[];
for isleep=1:4
 [~,groupPair,pval]=test_multigroup_pairwise(squeeze(ydatac(:,isleep,:))');
    for j=1:length(groupPair);groupPair{j}=groupPair{j}+(isleep-1)*5;end
   grouppairAll=[grouppairAll;groupPair]; pvalAll=[pvalAll;pval];
end
 sigstar(grouppairAll,pvalAll); hold on;
% axis(gca,'tight')
disp(pvalAll([2,5,8,11]));
 ylabel('Percentile');
set(gca,'xticklabelrotation',0,'box','off','xtick',2:5:20,...
        'xticklabel',{'Sleep1','Sleep2','Sleep3','Sleep4'},'ytick',0:20:100);
    legend(h,nameTags,'location','best')
setaxisformalAll(12,0);

% savepdf(f1,['/media/Big1/15tracks/figures/markovprediction',pop_tag1,'_per_addrun.pdf'])
% savepdf(f2,['/media/Big1/15tracks/figures/markovprediction',pop_tag1,'_per_addrun_barplot.pdf'])
% savepdf(f1,['/media/Big1/15tracks/figures/markovprediction',pop_tag1,'_per_addrun90.pdf'])
% savepdf(f2,['/media/Big1/15tracks/figures/markovprediction',pop_tag1,'_per_addrun90_barplot.pdf'])
savepdf(f3,['/media/Big1/15tracks/figures/markovprediction',pop_tag1,'_per_addrun90_barplot_dot.pdf'])
%%  fig 6gh; markov prediction of 15 track  allpeakcombo Add RUN
clear
savepath='/media/Big1/15tracks/selectFromMultipeak/';
% nameTags={'NoRun','AddRunSameOri','AddRun','AddRun90deg',...
%     'RunOnlySameOri','RunOnly90deg','RunOnly'   };
% nameTags={'NoRun','AddRun','AddRunSameOri'};
nameTags={'NoRun','AddRun90deg','AddRunSameOri'};
markov_tag='diff'; % fig 6g
% markov_tag='same';  % fig 6h


p4=cell(4,length(nameTags));
p4sm=cell(4,length(nameTags));
for imode=1:length(nameTags)
    saveNameTag=[nameTags{imode},'_allpkcombo','2','cell_',markov_tag,'pop_alongtime1by1'];
    
    load(fullfile(savepath,['allpeakcombosummary',saveNameTag,'.mat']),'allper');
    
    for isleep=1:4
        pers1=find([allper.isleep]==isleep);
        
        mse={allper(pers1).meanseper};
        % sey2=cell2mat(cellfun(@(x) x(:,2),mse,'UniformOutput',false)');
        my2=cell2mat(cellfun(@(x) x(:,1),mse,'UniformOutput',false)');
        p4{isleep,imode}=my2;

        mse={allper(pers1).meanseperSM};
        % sey2=cell2mat(cellfun(@(x) x(:,2),mse,'UniformOutput',false)');
        my2=cell2mat(cellfun(@(x) x(:,1),mse,'UniformOutput',false)');
        p4sm{isleep,imode}=my2;
    end
end

pvalAddNo_13=signrank(p4{1,3},p4{3,1});
pvalAddNo_14=signrank(p4{1,3},p4{4,1});
pvalAddNo_23=signrank(p4{2,3},p4{3,1});
pvalAddNo_24=signrank(p4{2,3},p4{4,1});


[p4m,p4se]=cellfun(@mean_se,p4);

N=length(p4{1});
CI95 = tinv([0.025 0.975], N-1);
p4ci95=cat(3,p4se.*CI95(1), p4se.*CI95(2));


f1=figure('color','w');
%        plot(p4m*100,'o-');
for i=1:size(p4,2)
    errorbar(p4m(:,i)*100,p4se(:,i)*100);hold on;
    %     errorbar((1:4)+(rand(1,4)-0.5)/5,p4m(:,i),p4ci95(:,i,2));hold on;
end
legend(nameTags)
set(gca,'xtick',1:4,'xlim',[0,5]);
xlabel('sleep');ylabel('percentile');
setaxisformalAll
%
f21=figure('color','w','position',[553    71   757   808]);
for isleep=1:4
    subplot(2,2,isleep)
    % [~,groupPair,pval]=test_multigroup_rank(p4(isleep,:));
    [~,groupPair,pval]=test_multigroup_pairwise(cell2mat(p4(isleep,:)));
    errorbarformal(1:length(nameTags),p4m(isleep,:)*100,p4se(isleep,:)*100,nameTags);
    sigstar(groupPair,pval)
    title(['sleep',num2str(isleep)]);
    ylabel('percentile');
    ylimdata=get(gca,'YLim');ylimdata(1)=[min(p4m(:))-max(p4se(:))]*100;
    set(gca,'xticklabelrotation',30,'ylim',ylimdata,'box','off');
    
end
setaxisformalAll
 

f2=figure('color','w','position',[ 109   361   544   440]);
fcolor=jet(3);
grouppairAll=[];pvalAll=[];ylimdata1=100;
for isleep=1:4
    h=[];
    for j=1:3
    h1=errorbarformal(j+(isleep-1)*5,p4m(isleep,j)*100,p4se(isleep,j)*100,[],fcolor(j,:),0.8); hold on;
    h=[h;h1(1)];
    end
   [~,groupPair,pval]=test_multigroup_pairwise(cell2mat(p4(isleep,:)));
    for j=1:length(groupPair);groupPair{j}=groupPair{j}+(isleep-1)*5;end
   grouppairAll=[grouppairAll;groupPair]; pvalAll=[pvalAll;pval];
   ylimdata1=min([ylimdata1,  [min(p4m(:))-max(p4se(:))]*100]);
end
 sigstar(grouppairAll,pvalAll); hold on;
 ylimdata=get(gca,'YLim');ylimdata=[ylimdata1-2,ylimdata(2)];
% axis(gca,'tight')
disp(pvalAll([2,5,8,11]));
 ylabel('percentile');
set(gca,'xticklabelrotation',0,'box','off','xtick',2:5:20,...
        'xticklabel',{'Sleep1','Sleep2','Sleep3','Sleep4'},'ylim',ylimdata,'ytick',0:10:100);
    legend(h,nameTags,'location','best')
setaxisformalAll(12,0);


f3=figure('color','w','position',[ 109   361   544   440]);
fcolor=jet(3);
grouppairAll=[];pvalAll=[];ylimdata1=100;
for isleep=1:4
    h=[];
    for j=1:3
    h1=errorbarformal(j+(isleep-1)*5,p4m(isleep,j)*100,p4se(isleep,j)*100,[],fcolor(j,:),0.8); hold on;
    h=[h;h1(1)];
    end
%    [~,groupPair,pval]=test_multigroup_pairwise(cell2mat(p4(isleep,:)));
%     for j=1:length(groupPair);groupPair{j}=groupPair{j}+(isleep-1)*5;end
%    grouppairAll=[grouppairAll;groupPair]; pvalAll=[pvalAll;pval];
   ylimdata1=min([ylimdata1,  [min(p4m(:))-max(p4se(:))]*100]);
end
sigstar({[3,11],[3,16],[8,11],[8,16]},[pvalAddNo_13,pvalAddNo_14,pvalAddNo_23,pvalAddNo_24]); hold on;
ylimdata=get(gca,'YLim');ylimdata=[ylimdata1-2,ylimdata(2)];
% axis(gca,'tight')
[pvalAddNo_13,pvalAddNo_14,pvalAddNo_23,pvalAddNo_24]
 ylabel('percentile');
set(gca,'xticklabelrotation',0,'box','off','xtick',2:5:20,...
        'xticklabel',{'Sleep1','Sleep2','Sleep3','Sleep4'},'ylim',ylimdata,'ytick',0:10:100);
    legend(h,nameTags,'location','best')
setaxisformalAll(12,0);

f4=figure('color','w','position',[ 109   361   544   440]);
ydata=p4sm';
ydata=ydata(:);
[ydata,gr]=cell2group(ydata);
% [m,se]=splitapply(@mean_se,ydata,gr);
xdata=[1,2,3,6,7,8,11,12,13,16,17,18];
% for ir=1:length(xdata);gr(gr==ir)=xdata(ir);end
[hdot,hbar]=plot_errorbar_with_data(ydata*100,gr,[],xdata); hold on;
% h=boxplot(ydata,gr,'symbol','.');
% distributionPlot(ydata,'groups',gr,'histOpt',1,'divFactor',15);
fcolor=jet(3);
set(hbar(1),'CData',repmat(fcolor,4,1),'EdgeColor','flat');
hbar(2)
grouppairAll=[];pvalAll=[];ylimdata1=100;
for isleep=1:4
 [~,groupPair,pval]=test_multigroup_pairwise(cell2mat(p4(isleep,:)));
    for j=1:length(groupPair);groupPair{j}=groupPair{j}+(isleep-1)*5;end
   grouppairAll=[grouppairAll;groupPair]; pvalAll=[pvalAll;pval];
   ylimdata1=min([ylimdata1,  [min(p4m(:))-max(p4se(:))]*100]);
end
 sigstar(grouppairAll,pvalAll); hold on;
% axis(gca,'tight')
disp(pvalAll([2,5,8,11]));
 ylabel('Percentile');
set(gca,'xticklabelrotation',0,'box','off','xtick',2:5:20,...
        'xticklabel',{'Sleep1','Sleep2','Sleep3','Sleep4'},'ytick',0:20:100);
    legend(h,nameTags,'location','best')
setaxisformalAll(12,0);


% fcolor=jet(3);
% grouppairAll=[];pvalAll=[];ylimdata1=100;
% for isleep=1:4
%     h=[];
%     for j=1:3
%     h1=errorbarformal(j+(isleep-1)*5,p4m(isleep,j)*100,p4se(isleep,j)*100,[],fcolor(j,:),0.8); hold on;
%     
%     h=[h;h1(1)];
%     end
%    ylimdata1=min([ylimdata1,  [min(p4m(:))-max(p4se(:))]*100]);
% end
% sigstar({[3,11],[3,16],[8,11],[8,16]},[pvalAddNo_13,pvalAddNo_14,pvalAddNo_23,pvalAddNo_24]); hold on;
% ylimdata=get(gca,'YLim');ylimdata=[ylimdata1-2,ylimdata(2)];
% % axis(gca,'tight')
% [pvalAddNo_13,pvalAddNo_14,pvalAddNo_23,pvalAddNo_24]
%  ylabel('percentile');
% set(gca,'xticklabelrotation',0,'box','off','xtick',2:5:20,...
%         'xticklabel',{'Sleep1','Sleep2','Sleep3','Sleep4'},'ylim',ylimdata,'ytick',0:10:100);
%     legend(h,nameTags,'location','best')
% setaxisformalAll(12,0);
% % savepdf(f1,['/media/Big1/15tracks/figures/markovprediction',markov_tag,'_allpeakcombo_addrun.pdf'])
% % savepdf(f2,['/media/Big1/15tracks/figures/markovprediction',markov_tag,'_allpeakcombo_addrun_barplot.pdf'])
% savepdf(f1,['/media/Big1/15tracks/figures/markovprediction',markov_tag,'_allpeakcombo_addrun90.pdf'])
% savepdf(f2,['/media/Big1/15tracks/figures/markovprediction',markov_tag,'_allpeakcombo_addrun90_barplot.pdf'])
savepdf(f4,['/media/Big1/15tracks/figures/markovprediction',markov_tag,'_allpeakcombo_addrun90_barplot_dot.pdf'])
% savepdf(f3,['/media/Big1/15tracks/figures/markovprediction',markov_tag,'_allpeakcombo_addrun90_barplot_AddNo.pdf'])
%%  markov prediction of 15 track allpeakcombo maze1 maze2

savepath='/media/Big1/15tracks/selectFromMultipeak/';

nameTags={'NoRun'};

p4=cell(4,2); % sleep x maze1/maze2

imode=1;
pop_tag='diff';
% pop_tag='same';
saveNameTag=[nameTags{imode},'_allpkcombo','2','cell_',pop_tag,'pop_alongtime1by1'];

load(fullfile(savepath,['allpeakcombosummary',saveNameTag,'.mat']),'allper');

for isleep=1:4
    pers1=find([allper.isleep]==isleep);
    for imaze=1:2
        mse={allper(pers1).meanseper};
        seqid1={allper(pers1).seqIDx};
        my2=cell2mat(cellfun(@(x,y) x([y.Maze]==imaze,1),mse,seqid1,'UniformOutput',false)');
        p4{isleep,imaze}=my2;
    end
end

[p4m,p4se]=cellfun(@mean_se,p4);

groupPairs2=cell(2,1);pval2=cell(2,1);
for i=1:2
    [~,groupPairs2{i},pval2{i}]=test_multigroup_pairwise(cell2mat(p4(:,i)'));
end

p14d={p4{4,1}-p4{1,1}, p4{4,2}-p4{1,2}};
[p14m,p14se]=mean_se_cell(p14d);
p14dpval=signrank(p14d{1},p14d{2});

p4pval=zeros(4,1);
for i=1:4
    p4pval(i)=signrank(p4{i,1},p4{i,2});
end

N=length(p4{1});
CI95 = tinv([0.025 0.975], N-1);
p4ci95=cat(3,p4se.*CI95(1), p4se.*CI95(2));

fcolor={'b','r'};
ylimdata=[min(p4m(:))-max(p4se(:)), max(p4m(:))+max(p4se(:))]*100;
f0=figure;
subplot(121)
h=[];
for j=1:2
h1=shadedErrorBar(1:4,p4m(:,j)*100,p4se(:,j)*100,fcolor{j},0.5);hold on; h=[h;h1.mainLine];
end
sigstar1(1:4,p4pval,max(p4m*100,[],2)+max(p4se*100,[],2));
tmp=get(gca,'Ylim');
 set(gca,'xtick',1:4,'xlim',[0,5],'ylim',[ylimdata(1),tmp(2)]);
    xlabel('sleep');ylabel('Percentile');
    subplot(122);
    errorbarformal(1:2,p14m,p14se);
    sigstar([1,2],p14dpval)
    xlabel('Maze');ylabel('\Delta Percentile(sleep4-sleep1)');
setaxisformalAll(12);

f1=figure('color','w','position',[ 303    78   705   657]);
ylimdata=[min(p4m(:))-max(p4se(:)), max(p4m(:))+max(p4se(:))]*100;
runx=[1.1,2.9;
    3.1,3.9];
for i=1:size(p4,2)
    subplot(2,2,i)
    h=patch([runx(i,:),runx(i,2),runx(i,1)],ylimdata([1,1,2,2]),'green','LineStyle','none',...
        'FaceAlpha',0.5);hold on;
    errorbar(p4m(:,i)*100,p4se(:,i)*100,'LineWidth',2,'Color','k');hold on;
    sigstar(groupPairs2{i},pval2{i});
    title(['Maze',num2str(i)]);
    tmp=get(gca,'Ylim');
    % legend({'Maze1','Maze2'},'location','best')
    set(gca,'xtick',1:4,'xlim',[0,5],'ylim',[ylimdata(1),tmp(2)]);
    xlabel('sleep');ylabel('Percentile');
    
    subplot(2,2,2+i)
    h=patch([runx(i,:),runx(i,2),runx(i,1)],ylimdata([1,1,2,2]),'green','LineStyle','none',...
        'FaceAlpha',0.5);hold on;
%     errorbar(p4m(:,i)*100,p4se(:,i)*100,'LineWidth',2,'Color','k');hold on;
    shadedErrorBar(1:4,p4m(:,i)*100,p4se(:,i)*100,{'k.-'},0.5);hold on;
%     sigstar(groupPairs2{i},pval2{i});
    title(['Maze',num2str(i)]);
    tmp=get(gca,'Ylim');
    % legend({'Maze1','Maze2'},'location','best')
    set(gca,'xtick',1:4,'xlim',[0,5],'ylim',[ylimdata(1),tmp(2)]);
    xlabel('sleep');ylabel('Percentile');
    
end
 
setaxisformalAll(12);
% savepdf(f1,['/media/Big1/15tracks/figures/markovprediction_',pop_tag,'maze12.pdf'])
% savepdf(f0,['/media/Big1/15tracks/figures/markovprediction_',pop_tag,'maze12_diff14.pdf'])